<?php

namespace app\index\model;

define('VENDOR_PATH',__DIR__.'/vendor/');

if (is_file(VENDOR_PATH .'aliyuncs/oss-sdk-php/autoload.php')) {
    require_once VENDOR_PATH . 'aliyuncs/oss-sdk-php/autoload.php';
}

if (is_file(VENDOR_PATH.'autoload.php')) {
    require_once VENDOR_PATH . 'autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;
use think\Config;

class Oss
{
    //主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议创建并使用RAM账号进行API访问或日常运维。
    // 阿里云账号AccessKey
    private $accessKeyId;
    private $accessKeySecret;
    // Endpoint:Region
    private $endpoint;
    // 存储空间名称
    private $bucket;

    private $ossClient;

    public function __construct()
    {
        $config = Config::get('aliyun');
        $this->accessKeyId = $config['accessKeyId'];
        $this->accessKeySecret = $config['accessKeySecret'];
        $this->endpoint = $config['endpoint'];
        $this->bucket = $config['bucket'];
        try {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        }catch (OssException $e) {
            throw $e;
        }
    }

    public function uploadFile($filePath,$objectName,$unlink = true) // unlink 是否需要删除本地文件
    {
        try{
            $result = $this->ossClient->uploadFile($this->bucket,$objectName,$filePath);
        }catch (OssException $e) {
            throw $e;
        }
        if($unlink) {
            unlink($filePath);
        }
        return $result;
    }

    public function appendFile($filePaths,$objectName)
    {
        try {
            $position = 0;
            foreach ($filePaths as $key => $value) {
                $position = $this->ossClient->appendFile($this->bucket,$objectName,$value,$position);
            }
        }catch (OssException $e) {
            throw $e;
        }
    }

}